package com.ming.sportdemo.controller;

import com.alibaba.fastjson.JSON;
import com.ming.sportdemo.bean.QueryInfo;
import com.ming.sportdemo.bean.Util;
import com.ming.sportdemo.common.Result;
import com.ming.sportdemo.config.ServerConfig;
import com.ming.sportdemo.service.UtilService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

@CrossOrigin
@RestController
public class UtilController {
    @Autowired
    private UtilService utilService;
    @Autowired
    private ServerConfig serverConfig;

    @RequestMapping("/allUtil")
    public String getUtilList(HttpServletRequest request, QueryInfo queryInfo){
//        System.out.println(queryInfo.getPageNum());
        //获取最大列表数和当前编号
        System.out.println(""+queryInfo.getType());
        int numbers = utilService.getUtilCounts("%"+queryInfo.getQuery()+"%");
        int pageStart = (queryInfo.getPageNum() - 1) * queryInfo.getPageSize();
        List<Util> utils = utilService.getAllUtil("%" + queryInfo.getQuery() + "%","%" + queryInfo.getType() + "%",pageStart, queryInfo.getPageSize());
        HashMap<String, Object> res = new HashMap<>();
        res.put("numbers",numbers);
        res.put("data",utils);
        String res_string = JSON.toJSONString(res);
        return res_string;
    }

    @RequestMapping("/updateUtil")
    public String updateUtil(@RequestBody Util util){
        System.out.println(util);
        String url = UploadController.baseURL;
        String baseurl = serverConfig.getPort();
        if((baseurl+url).equals(util.getUtilView())){
            util.setUtilView(url);
        }
        int i = utilService.updateUtil(util);
        System.out.println(i);
        System.out.println(util);
        return i>0?"success":"error";
    }

    @RequestMapping("/addUtil")
    public String addUtil(@RequestBody Util util){
        String url=UploadController.baseURL;
        util.setUtilView(url);
        int i = utilService.addUtil(util);
        return i>0?"success":"error";
    }

    @RequestMapping("/deleteUtil")
    public Result deleteUtil(int utilId){
        System.out.println(utilId);
        int i = utilService.deleteUtil(utilId);
        String res = i>0?"success":"error";
        if(res.equals("success")){
            return Result.succ(res);
        }else {
            return Result.fail(res);
        }
    }
    @RequestMapping("/allUtilName")
    public String allUtilName(){
        List<Util> utils = utilService.list();
        HashMap<String,Object> map = new HashMap<>();
        List<String> names = new LinkedList<>();
        for (int i = 0; i < utils.size(); i++) {
            names.add(utils.get(i).getUtilName());
        }
        map.put("data",names);
        String res = JSON.toJSONString(map);
        return res;
    }

}
